#include <57header.h>

int flag=0; // 0:还没有进行加票, 1: 已经加票
int num = 20;
pthread_mutex_t lock;
pthread_cond_t cond;

void *sellFun(void *p){
    sleep(1);

    while(1){

        pthread_mutex_lock(&lock);
        if(num <= 0 && flag ==1){
            pthread_mutex_unlock(&lock);
            printf("票卖完了 \n");
            break;
        }

        // 走到这: 票还没有卖完
        struct timeval nowTime;
        gettimeofday(&nowTime, NULL);
        srand((unsigned int) nowTime.tv_usec );
        double rand_num = (double)rand()/RAND_MAX;

        if(rand_num < 0.5 && num > 0){
            num--;
            printf("卖出一张票, 还剩余: %d \n", num);
        }

        // 票数小于5张, 没有加过票 -> 唤醒加票程序
        if(num < 5 && flag == 0){
            pthread_cond_signal(&cond);
        }

        pthread_mutex_unlock(&lock);
        //usleep(20);

        printf("sell");
    }
    return NULL;
}

void *addFun(void *p){

    pthread_mutex_lock(&lock);
    if(num < 5 ){
        // 票数小于5张
        num = num+10;
        flag = 1;
    }else{
        // 票数大于等于5张
        pthread_cond_wait(&cond, &lock);
        num = num + 10;
        flag = 1;
    }
    pthread_mutex_unlock(&lock);

    return NULL;
}
int main(int argc,char*argv[])
{
    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&cond, NULL);

    pthread_t son1, son2;
    pthread_create(&son1, NULL, sellFun,NULL);
    pthread_create(&son2, NULL, addFun,NULL);

    pthread_join(son1, NULL);
    pthread_join(son2, NULL);
    return 0;
}

